
const { mysql } = require('../qcloud')
const config = require('../config')
const WXBizDataCrypt = require('../utils/WXBizDataCrypt')

const serviceConfig = config.service

async function updateSharedGroup(ctx, next) {
  const body = ctx.request.body
  const openId = body.open_id
  // Get session_key
  const sessionKeys = await mysql('cSessionInfo').select('session_key').where('open_id', openId)
  if ( sessionKeys && sessionKeys.length > 0) {
    const data = body.data
    const sessionKey = sessionKeys[0].session_key

    // Use session_key to get open_group_id
    const pc = new WXBizDataCrypt(config.appId, sessionKey)
    const groupInfo = pc.decryptData(data.encryptedData , data.iv)
    const openGId = groupInfo.openGId

    // Update sharedGroup table
    const sharedGroupTable = mysql('sharedGroup')
    const sharedGroups = await sharedGroupTable
      .select('*')
      .where('open_id', openId)
      .andWhere('openGId', openGId)
    if (sharedGroups && sharedGroups.length > 0) {
      const sharedGroup = sharedGroups[0]
      if (sharedGroup.timestamp + serviceConfig.validSharedTime < new Date().getTime()) {
        await sharedGroupTable
          .update('timestamp', new Date().getTime())
          .where('open_id', openId)
          .andWhere('openGId', openGId)
      }
    } else {
      const sharedData = {
        open_id: openId,
        openGId: openGId,
        timestamp: new Date().getTime()
      }
      await sharedGroupTable.insert(sharedData)

      const recordTable = mysql('record')
      await recordTable.where('open_id', openId).increment('gold', serviceConfig.validSharedGold)
    }
    ctx.state.data = 'shared successful'

  }
}

module.exports = {
  updateSharedGroup
}
